

CREATE SCHEMA scipg;


CREATE OR REPLACE FUNCTION scipg.round(float8, int4)
  RETURNS float8 AS
$BODY$

       select cast(round(cast($1 as numeric),$2) as double precision);

$BODY$
  LANGUAGE 'sql' IMMUTABLE;
GRANT EXECUTE ON FUNCTION scipg.round(float8, int4) TO public;
COMMENT ON FUNCTION scipg.round(float8, int4) IS 'round function does not work on  double precision numbers by default.  This function casts the argument as a numeric.';



CREATE OR REPLACE FUNCTION scipg.range(int4, int4)
  RETURNS SETOF int4 AS
$BODY$
declare
        s alias for $1;
        e alias for $2;
        d int;
begin
        d := s;

        while d <= e
        LOOP
                return next d;
                select d + 1 into d;
        END LOOP;
  return; 
end;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;
GRANT EXECUTE ON FUNCTION scipg.range(int4, int4) TO public;
COMMENT ON FUNCTION scipg.range(int4, int4) IS 'Generate a table of values ranging from $1 to $2.';


CREATE OR REPLACE FUNCTION scipg.range(float4, float4, float4)
  RETURNS SETOF float4 AS
$BODY$
declare
        s alias for $1;
        e alias for $2;
        d float;
begin
        d := s;

        while d <= e
        LOOP
                return next d;
                select d + $3 into d;
        END LOOP;
  return; 
end;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;
GRANT EXECUTE ON FUNCTION scipg.range(float4, float4, float4) TO public;
COMMENT ON FUNCTION scipg.range(int4, int4) IS 'Generate a table of values ranging from $1 to $2, step by $3.';


CREATE OR REPLACE FUNCTION scipg."first"(anyelement, anyelement)
  RETURNS anyelement AS
'select $1'
  LANGUAGE 'sql' IMMUTABLE STRICT;
COMMENT ON FUNCTION scipg."first"(anyelement, anyelement)
 IS 'Return the first of two values. Used to implement the first aggregation function';

CREATE AGGREGATE scipg."first"(
  BASETYPE=anyelement,
  SFUNC=scipg."first",
  STYPE=anyelement
);

CREATE OR REPLACE FUNCTION scipg."last"(anyelement, anyelement)
  RETURNS anyelement AS
'select $1'
  LANGUAGE 'sql' IMMUTABLE STRICT;
COMMENT ON FUNCTION scipg."last"(anyelement, anyelement)
 IS 'Return the second of two values. Used to implement the last aggregation function';

CREATE AGGREGATE scipg."last"(
  BASETYPE=anyelement,
  SFUNC=scipg."last",
  STYPE=anyelement
);



CREATE OR REPLACE FUNCTION scipg.tableexists(schemaname text, tablename text)
  RETURNS boolean AS
$BODY$
select EXISTS (
SELECT c.relname 
  from pg_class c, pg_namespace n
 where c.relname = $2 
   and c.relnamespace = n.oid
   and n.nspname = $1
)
$BODY$
  LANGUAGE 'sql' VOLATILE;
